package com.maimao.search.controller;

import com.google.common.collect.Lists;
import com.maimao.core.model.resp.Result;
import com.maimao.search.model.goods.EsGoods;
import com.maimao.search.model.goods.GoodsSearch;
import com.maimao.search.model.goods.SearchPageResult;
import com.maimao.search.service.GoodsSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/12/27 8:11 下午
 */
@RequestMapping("/search/goods")
@RestController
public class GoodsSearchController {

    @Autowired
    private GoodsSearchService goodsSearchService;

    /**
     * 搜索自动补全
     */
    @GetMapping("/suggest")
    public Result<?> searchSuggestions(@RequestParam("key") String key) {
        if (StringUtils.isEmpty(key)) {
            return Result.notValid();
        }
        return Result.okData(goodsSearchService.searchSuggestions(key));
    }

    @PostMapping("/search")
    public SearchPageResult<EsGoods> search(@RequestBody GoodsSearch goodsSearch) {
        if (StringUtils.isEmpty(goodsSearch.getKey()) && (goodsSearch.getCid3() == null || goodsSearch.getCid3() < 1)) {
            return new SearchPageResult<EsGoods>(Lists.newArrayList(), 0L);
        }
        if (goodsSearch.getPage() == null || goodsSearch.getPage() < 1) {
            goodsSearch.setPage(1);
        }
        if (goodsSearch.getSize() == null || goodsSearch.getSize() < 1) {
            goodsSearch.setSize(50);
        }

        return goodsSearchService.searchGoods(goodsSearch);

    }
}
